import { Transaction } from 'web3-core/types';
import Web3 from 'web3';
import { ethNodeUrl } from '../../global';
import { EthUserAddress, EthCoinType } from '../../database/eth/EthDatabase';
import dec from 'decimal.js';
const web3 = new Web3(ethNodeUrl);

class EthModel {

  /**
   * 创建一个地址
   * @param {(number|string)} uid
   * @returns
   * @memberof EthModel
   */
  async createEthAddress(uid:number|string) {
    const addressObj = web3.eth.accounts.create();
    const address = await EthUserAddress.saveUserAddress(uid, addressObj.address, addressObj.privateKey);
    return address;
  }

  /**
   * 返回eth余额
   * @param address 
   */
  async getAddressEthAmount(address: string) {
    try {
      web3.utils.toChecksumAddress(address)
      const amount = await web3.eth.getBalance(address);
      return web3.utils.fromWei(amount, 'ether');  
    } catch (error) {
      return false;
    }
  }

  async getTransactionReceipt(hash: string) {
    try {
      let receipt = await web3.eth.getTransactionReceipt(hash);
      if(receipt.logs.length) {
        // 解析参数
        const TokenAmountWei = web3.eth.abi.decodeParameter('uint256', receipt.logs[0].data);
        // 获取小数点
        const decimal = await EthCoinType.getContractDecimal(receipt.logs[0].address);
        // 计算具体数值
        const amount = new dec(String(TokenAmountWei)).div(10**decimal);
        const to = web3.eth.abi.decodeParameter('address', String(receipt.logs[0].topics[2]));
  
        //  构建数据
        const transactionMessage = {
          hash: receipt.transactionHash,
          blockNum: receipt.blockNumber,
          contract: receipt.logs[0].address,
          from: receipt.from,
          to: String(to),
          amount: amount.toString()
        };
        return transactionMessage;
      }else{
        let receipt = await web3.eth.getTransaction(hash) as any;
        const transactionMessage = {
          hash: receipt.hash,
          blockNum: receipt.blockNumber,
          contract: null,
          from: receipt.from,
          to: receipt.to,
          amount: web3.utils.fromWei(receipt.value, 'ether')
        };
        return transactionMessage;
      }
      
    } catch (error) {
      throw error;
    }
  }

}

// var test = new EthModel;
// test.createEthAddress(1).then(console.log);

export default EthModel;